import { Component, OnInit, Input,ElementRef, ViewContainerRef,AfterViewInit,OnDestroy } from '@angular/core';
import { ModelContainerService } from '../../services/model-container.service';
import { DataTransmissionService } from '../../services/data-transmission.service';
import { FormControl, FormGroup, FormArray, FormBuilder } from '@angular/forms';

import { Ng4FilesStatus, Ng4FilesSelected } from 'angular4-files-upload';
import { GeoData, postData, ToolIOData, uploadResponseData, LayerItem } from '../../data_model/data-model';
import {Subscription} from 'rxjs'


import { ToastsManager } from 'ng2-toastr/ng2-toastr';
@Component({
  selector: 'app-tool-panel',
  templateUrl: './tool-panel.component.html',
  styleUrls: ['./tool-panel.component.css']
})


export class ToolPanelComponent implements OnInit ,AfterViewInit,OnDestroy{

  @Input("ToolId")
  public ToolId: any;
  public title: any;
  public selectedFilesArray;
  public selectedFiles;

  public AllRequestData: ToolIOData;
  public DataForUpload: Map<string, File>;
  public inputDataArray: Array<GeoData>;
  public LayerItems: Array<LayerItem>;
  public LayerListSubscription:Subscription;
  public ReadySubscription:Subscription;

  public DataArrayInLayerList: any;

  private responseData;


  public filesSelect(selectedFiles: Ng4FilesSelected, inputDataName: string, myform: any): void {
    if (selectedFiles.status !== Ng4FilesStatus.STATUS_SUCCESS) {
      this.selectedFilesArray = selectedFiles.status;
      // Hnadle error statuses here

    }

    this.selectedFilesArray = selectedFiles.files;
    let selectFile = Array.from(selectedFiles.files).map(file => file)[0];
    this.DataForUpload.set(inputDataName, selectFile);
    this.checkInputState();
  }

  constructor(public toastr: ToastsManager,
    private modelContainerService: ModelContainerService,
    private dataTransmissionService: DataTransmissionService) {
    this.DataForUpload = new Map<string, File>();
    this.LayerItems = [];
  }

  ngOnInit() {
    this.inputDataArray = new Array<GeoData>();

    this.LayerListSubscription =  this.dataTransmissionService.getLayerListSubject().subscribe(layersArray => {
      this.LayerItems = layersArray;
    })

    if (this.ToolId) {
      this.modelContainerService.getModelInfo(this.ToolId).then(data => {
        this.AllRequestData = data;
        this.inputDataArray = data.input;
      }, (error => {
        this.toastr.error("request method failed.", "ERROR", {
          toastLife: 6000
        })
        console.log(error);
      }));

     this.ReadySubscription =  this.dataTransmissionService.getReadySubject().subscribe(next => {
        this.onSubmit();
      })
    }
   
  }

  ngAfterViewInit(){
   
    this.dataTransmissionService.sendReqAllLayerData();
  }

  checkInputState() {
    if (this.DataForUpload.size === this.inputDataArray.length) {
      this.dataTransmissionService.sendPreparedStateSubject(true);
    }
  }

  onSubmit() {
    console.log("submit");
    let postDataArray = new Array<postData>();
    this.DataForUpload.forEach((value, key) => {
      postDataArray.push(
        new postData(this.AllRequestData.stateId,
          this.AllRequestData.stateName,
          this.AllRequestData.stateDesc,
          key,
          value));
    })
    this.modelContainerService.uploadInputData(postDataArray).then((responseData) => {
      this.responseData = responseData;
      this.onRun();
    })
  }

  onRun() {
    this.modelContainerService.runModel(this.ToolId, this.responseData).then(msr_id => {
      this.onWaitModelRun(msr_id);
    }).catch(reason => {
      console.log(reason);
    })
  }
  onWaitModelRun(msr_id: string) {
    this.modelContainerService.waitForResult(msr_id).then(data => {
      console.log(data);
    })
  }

  ngOnDestroy(){
    this.LayerListSubscription.unsubscribe();
    this.ReadySubscription.unsubscribe();
  }

}
